from django import http
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.areas.models import Area
from utils.response_code import RETCODE
from utils.views import LoginRequiredJSONMixin
from django.core.cache import cache

# 显示省市区
class AreaView(LoginRequiredJSONMixin,View):
    def get(self,request):
        # 判断是不是省,有area_id的是市区
        area_id = request.GET.get('area_id')
        if area_id is None:
            # 如果parent_id为空,那么是省,这是一个queryset.
            pro_list=cache.get('pro')
            if pro_list is None:
                provinces = Area.objects.filter(parent__isnull=True)
                pro_list= []
                # 遍历这个set,得到省对象
                for province in provinces:
                    pro_list.append({
                        'id':province.id,
                        'name':province.name
                    })
                    cache.set('pro',pro_list,24*3600)
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', 'pro_list': pro_list})
        else:
            # 根据area_id获取城市的queryset
            cities_list=cache.get('area_list%s'%area_id)
            if cities_list is None:
                cities = Area.objects.filter(parent_id=area_id)
                cities_list = []
                for city in cities:
                    cities_list.append({
                        'id':city.id,
                        'name':city.name
                    })
                cache.set('cities_list%s'%area_id,cities_list,24*3600)
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', 'cities': cities_list})
